<template>
  <div class="article-detail">
    <el-container>
      <el-header>
        <nav-bar></nav-bar>
      </el-header>
      <el-main>
        <div class="article-content" v-if="article">
          <div class="article-header">
            <h1 class="article-title">{{ article.title }}</h1>
            <div class="article-meta">
              <el-avatar :size="32" :src="avatarUrl"></el-avatar>
              <div class="meta-info">
                <!-- Fix: Add optional chaining and default value -->
                <span class="author">{{ article.author?.username || '匿名用户' }}</span>
                <span class="date">{{ formatDate(article.createdAt) }}</span>
              </div>
            </div>
          </div>

          <div class="article-body markdown-body" v-html="renderedContent"></div>

          <div class="article-actions">
            <el-button 
              :class="['custom-like-btn', article.isLiked ? 'liked' : '']"
              @click="handleLike" 
              :disabled="!isAuthenticated"
            >
              <span v-if="!article.isLiked">❤️ 点赞</span>
              <span v-else>✅ 已点赞</span>
              <!-- 修改：显示点赞人数组的长度（人数） -->
              <span class="like-count">{{ article.likes?.length || 0 }}</span>
            </el-button>
          </div>

          <div class="comments-section">
            <h3>评论</h3>
            <div class="comment-form" v-if="isAuthenticated">
              <el-input
                v-model="commentContent"
                type="textarea"
                :rows="3"
                placeholder="写下你的评论..."
              />
              <el-button type="primary" @click="submitComment" :loading="submitting">
                发表评论
              </el-button>
            </div>
            <div class="login-tip" v-else>
              <router-link to="/login">登录</router-link> 后参与评论
            </div>

            <div class="comments-list">
              <div v-for="comment in comments" :key="comment.id" class="comment-item">
                <div class="comment-header">
                  <!-- 修改：从 comment.user 获取用户名生成头像 -->
                  <el-avatar 
                    :size="24" 
                    :src="getAvatarUrl(comment.user?.username || '匿名用户')"
                  ></el-avatar>
                  <!-- 修改：从 comment.user 获取用户名 -->
                  <span class="comment-author">
                    {{ comment.user?.username || '匿名用户' }}
                  </span>
                  <span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
                </div>
                <div class="comment-content">
                  {{ comment.content }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="loading-container">
          <el-empty description="文章不存在或已被删除" v-if="!loading"></el-empty>
          <el-skeleton :rows="10" animated v-else />
        </div>
      </el-main>
      <el-footer>
        <footer-component></footer-component>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import NavBar from '../components/NavBar.vue'
import FooterComponent from '../components/FooterComponent.vue'

export default {
  name: 'ArticleDetail',
  components: {
    NavBar,
    FooterComponent
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    const loading = ref(true)
    const submitting = ref(false)
    const commentContent = ref('')
    
    // 调整顺序：先声明 article 计算属性
    const article = computed(() => store.getters.getCurrentArticle)
    // 再声明依赖 article 的 comments 计算属性
    const comments = computed(() => article.value?.comments || [])  // 修复后顺序

    const isAuthenticated = computed(() => store.getters.isAuthenticated)
    const currentUser = computed(() => store.getters.currentUser)
    console.log(article,  isAuthenticated, currentUser );
    
    const avatarUrl = computed(() => {
      return article.value
        ? `https://ui-avatars.com/api/?name=${encodeURIComponent(article.value.author.username)}&background=random`
        : ''
    })

    const renderedContent = computed(() => {
      if (!article.value) return ''
      
      marked.setOptions({
        highlight: function(code, lang) {
          if (lang && hljs.getLanguage(lang)) {
            return hljs.highlight(code, { language: lang }).value
          }
          return hljs.highlightAuto(code).value
        },
        breaks: true
      })

      return marked(article.value.content)
    })

    onMounted(async () => {
      try {
        // 假设路由配置参数名为 `articleId`，则修改为：
        const articleId = route.params.id;
        console.log(route.params.id);
        
        if (!articleId) {
          throw new Error('文章ID不存在');
        }
        console.log('Fetching article with ID:', articleId)
        loading.value = true
        const response = await store.dispatch('fetchArticleById', articleId)
        console.log('Article response:', response)
      } catch (error) {
        console.error('获取文章失败：', error)
        ElMessage.error(error.message || '获取文章失败')
      } finally {
        loading.value = false
      }
    })

    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const getAvatarUrl = (username) => {
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random`
    }

    // 点赞方法
    const handleLike = async () => {
      if (!isAuthenticated.value) {
        ElMessage.warning('请先登录')
        return
      }
      if (!article.value?._id) {
        ElMessage.warning('文章ID不存在，无法点赞')
        return
      }

      try {
        const response = await store.dispatch('likeArticle', article.value._id)
        // 关键修改：点赞成功后重新获取文章详情，更新 Vuex 状态
        await store.dispatch('fetchArticleById', article.value._id)
        ElMessage.success(article.value.isLiked ? '点赞成功' : '取消点赞成功')
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }

    // 提交评论方法
    const submitComment = async () => {
      if (!commentContent.value.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }
      // 新增：校验文章ID是否存在
      if (!article.value?._id) {
        ElMessage.warning('文章ID不存在，无法发表评论')
        return
      }

      submitting.value = true
      try {
        await store.dispatch('createComment', {
          articleId: article.value._id,
          content: commentContent.value
        })
        await store.dispatch('fetchArticleById', article.value._id)
        commentContent.value = ''
        ElMessage.success('评论成功')
      } catch (error) {
        ElMessage.error('评论失败')
      } finally {
        submitting.value = false
      }
    }

    return {
      article,
      loading,
      avatarUrl,
      renderedContent,
      isAuthenticated,
      currentUser,
      commentContent,
      comments,
      submitting,
      // 移除图标库相关的点赞图标导出
      formatDate,
      getAvatarUrl,
      handleLike,
      submitComment
    }
  }
}
</script>

<style scoped>
.article-detail {
  min-height: 100vh;
}

.el-header {
  padding: 0;
  height: auto;
}

.el-main {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.article-content {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.article-header {
  margin-bottom: 30px;
}

.article-title {
  margin: 0 0 20px;
  font-size: 2em;
  color: #303133;
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.meta-info {
  display: flex;
  flex-direction: column;
}

.author {
  font-weight: 500;
  color: #303133;
}

.date {
  font-size: 0.9em;
  color: #909399;
}

.article-body {
  line-height: 1.8;
  color: #303133;
  margin: 30px 0;
}

.article-actions {
  margin: 30px 0;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.comments-section {
  margin-top: 40px;
  border-top: 1px solid #dcdfe6;
  padding-top: 20px;
}

.comments-section h3 {
  margin-bottom: 20px;
  color: #303133;
}

.comment-form {
  margin-bottom: 30px;
}

.comment-form .el-button {
  margin-top: 10px;
}

.login-tip {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.login-tip a {
  color: #409EFF;
  text-decoration: none;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #303133;
}

.comment-date {
  font-size: 0.9em;
  color: #909399;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
}

.loading-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.markdown-body) {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
}

:deep(.markdown-body pre) {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
}

:deep(.markdown-body code) {
  background-color: rgba(175,184,193,0.2);
  border-radius: 6px;
  padding: 0.2em 0.4em;
  font-size: 85%;
}

:deep(.markdown-body pre code) {
  background-color: transparent;
  padding: 0;
}
</style>

<style scoped>
/* 新增点赞按钮样式 */
.custom-like-btn {
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s;
}

.custom-like-btn.liked {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: white;
}

.custom-like-btn:not(.liked) {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.like-count {
  margin-left: 6px;
  font-size: 0.9em;
}
</style>